from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.hashers import make_password
from django.contrib.auth import authenticate, login, logout
from app.users.models import User

from django.contrib.auth.models import Permission

import re

from django import forms


class LoginForm(forms.Form):
    username = forms.CharField(required=True, error_messages={"required": "请填写用户名"})
    password = forms.CharField(required=True, error_messages={"required": u"请填写密码"})


class UserCreateForm(forms.Form):
    username = forms.CharField(label='username', max_length=30)
    password = forms.CharField(label='password', max_length=30)
    email = forms.CharField(label='email', max_length=50)
    mobile = forms.CharField(label='mobile', max_length=11)
    is_active = forms.CharField(label='is_active', max_length=1)

    error_messages = {
        "username": {"required": "用户名不能为空"},
        "password": {"required": "密码不能为空"},
        "email": {"required": "邮箱不能为空"},
        "phone": {"required": "电话不能为空"},
        "is_active": {"required": "状态不能为空"},
    }

    def clean(self):
        cleaned_data = super(UserCreateForm, self).clean()
        username = cleaned_data.get('username')
        email = cleaned_data.get('email')
        mobile = cleaned_data.get('mobile')

        if User.objects.filter(username=username).count():
            raise forms.ValidationError('用户名：{}已存在'.format(username))

        if User.objects.filter(email=email).count():
            raise forms.ValidationError('邮箱：{}已存在'.format(email))

        if User.objects.filter(mobile=mobile).count():
            raise forms.ValidationError('电话：{}已存在'.format(mobile))


@login_required
def user_index(request):
    user_obj = User.objects.get(username=request.user)
    data = {
        'username': user_obj.username,
        'email': user_obj.email,
    }
    return render(request, 'users/index.html', {'data': data})


def user_logout(request):
    logout(request)
    return HttpResponseRedirect('/users/login')

def user_login(request):
    if request.method == 'GET':
        return render(request, 'users/login.html')
    elif request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            return HttpResponseRedirect('/users/index')
        else:
            msg = "用户名或密码错误！"
            ret = {"msg": msg, "login_form": LoginForm}
            return render(request, "users/login.html", {'data': ret})


@login_required
def user_add(request):
    if request.method == 'GET':
        print(request.path)
        return render(request, 'users/register.html')
    elif request.method == 'POST':
        user_create_form = UserCreateForm(request.POST)
        if user_create_form.is_valid():
            data = user_create_form.cleaned_data
            data['password'] = make_password(data['password'])
            User.objects.create(**data)
            message = "创建用户成功"
        else:
            pattern = '<li>.*?<ul class=.*?><li>(.*?)</li>'
            errors = str(user_create_form.errors)
            user_create_form_errors = re.findall(pattern, errors)
            message = "创建用户失败, {}".format(user_create_form_errors)
        res = {
            "status": "success",
            "message": message,
        }
        return JsonResponse(res)


@login_required
def user_list(request):
    print(request.user)
    querset = User.objects.all()
    user_list = []
    for i in querset:
        user_list.append({
            'id': i.id,
            'username': i.username,
            'email': i.email,
            'mobile': i.mobile,
        })
    return render(request, 'users/user_list.html', {'user_list': user_list})


@login_required
def user_edit(request):
    user = User.objects.get(username=request.user)
    if user.has_perm('users.change_user_per'):
        data = {
            'code': '0',
            'message': '修改成功'
        }
    else:
        data = {
            'code': '1',
            'message': '对不起，您没有权限'
        }
    return JsonResponse(data)

# 获取用户权限并检测（适用于单个用户权限）
@login_required
def user_permission_1(request):
    users = User.objects.get(username=request.user)
    user_perms = users.has_perm('users.change_user_per')
    if user_perms:
        message = '恭喜你，您拥有查看此页面的权限'
    else:
        message = '对不起，您没有权限查看此页面'
    return render(request, 'users/permission_1.html', {'data': message})

@permission_required('users.del_user_per', '/users/page_error')
def user_permission_2(request):
    return HttpResponse('您拥有查看此页面的权限')

@login_required
def user_permission_3(request):
    return render(request, 'users/permission_3.html')

@login_required
def user_page_error(request):
    return HttpResponse('page 403 forbidden')